package com.neusoft.yuejian26.yuejian_26.Activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.neusoft.yuejian26.yuejian_26.Bean.Result;
import com.neusoft.yuejian26.yuejian_26.Other.CacheInfo;
import com.neusoft.yuejian26.yuejian_26.R;
import com.neusoft.yuejian26.yuejian_26.model.PostModel;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class PostActivity extends AppCompatActivity {

    public ImageView svg_back,post_pic;
    public EditText post_content;
    public LinearLayout add_postpic;
    public RelativeLayout btn_post;
    public String uid=null;
    public String filePath = null;

    private Bitmap mBitmap;

    protected static final int CHOOSE_PICTURE = 0;
    protected static final int TAKE_PICTURE = 1;
    protected static Uri tempUri;
    private static final int CROP_SMALL_PICTURE = 2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_post);
        intview();
        intEvent();
    }

    private class subPost implements View.OnClickListener{

        @Override
        public void onClick(View view) {
            String pcontent = post_content.getText().toString();
            if(pcontent.equals("")){
                Toast.makeText(PostActivity.this,"请填写发帖内容",Toast.LENGTH_SHORT).show();
            }
            else {
                upLoadPpicFile(filePath);
            }
        }
    }

    /**
     * 显示修改图片的对话框
     */
    protected void showChoosePicDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(PostActivity.this);
        builder.setTitle("上传图片");
        String[] items = { "选择本地照片", "拍照" };
        builder.setNegativeButton("取消", null);
        builder.setItems(items, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    case CHOOSE_PICTURE: // 选择本地照片
                        Intent openAlbumIntent = new Intent(
                                Intent.ACTION_GET_CONTENT);
                        openAlbumIntent.setType("image/*");
                        //用startActivityForResult方法，待会儿重写onActivityResult()方法，拿到图片做裁剪操作
                        startActivityForResult(openAlbumIntent, CHOOSE_PICTURE);
                        break;
                    case TAKE_PICTURE: // 拍照
                        Intent openCameraIntent = new Intent(
                                MediaStore.ACTION_IMAGE_CAPTURE);
                        tempUri = Uri.fromFile(new File(Environment
                                .getExternalStorageDirectory(), "temp_image.jpg"));
                        // 将拍照所得的相片保存到SD卡根目录
                        openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, tempUri);
                        startActivityForResult(openCameraIntent, TAKE_PICTURE);
                        break;
                }
            }
        });
        builder.show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == MainActivity.RESULT_OK) {
            switch (requestCode) {
                case TAKE_PICTURE:
                    cutImage(tempUri); // 对图片进行裁剪处理
                    break;
                case CHOOSE_PICTURE:
                    cutImage(data.getData()); // 对图片进行裁剪处理
                    break;
                case CROP_SMALL_PICTURE:
                    if (data != null) {
                        setImageToView(data); // 让刚才选择裁剪得到的图片显示在界面上
                    }
                    break;
            }
        }
    }
    /**
     * 裁剪图片方法实现
     */
    protected void cutImage(Uri uri) {
        if (uri == null) {
            Log.i("alanjet", "The uri is not exist.");
        }
        tempUri = uri;
        Intent intent = new Intent("com.android.camera.action.CROP");
        //com.android.camera.action.CROP这个action是用来裁剪图片用的
        intent.setDataAndType(uri, "image/*");
        // 设置裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 3);
        intent.putExtra("aspectY", 2);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 200);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, CROP_SMALL_PICTURE);
    }
    /**
     * 保存裁剪之后的图片数据
     */
    protected void setImageToView(Intent data) {
        Bundle extras = data.getExtras();
        if (extras != null) {
            mBitmap = extras.getParcelable("data");
            //这里图片是方形的，可以用一个工具类处理成圆形（很多头像都是圆形，这种工具类网上很多不再详述）
            post_pic.setImageBitmap(mBitmap);//显示图片
            //在这个地方可以写上上传该图片到服务器的代码，后期将单独写一篇这方面的博客，敬请期待...
            filePath = saveMyBitmap("1",mBitmap);
        }
    }

    /*上传用户头像*/
    private void upLoadPpicFile(String filePath) {
        /*Log.i("xxxxxxxxxx",filePath);*/
        String ptext = post_content.getText().toString();
        /*Log.i("xxxxxxxxxx1",ptext);*/
        File file = new File(filePath);
        /*Log.i("xxxxxxxxxx1",file.getName());*/
        RequestBody requestFile =
                RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part body =
                MultipartBody.Part.createFormData("file", file.getName(), requestFile);
        uid = new CacheInfo(this).getUserIdCache();
        Call<Result> call = new PostModel().upLoadPpic(uid,ptext,body);
        call.enqueue(new Callback<Result>() {
            @Override
            public void onResponse(Call<Result> call,
                                   Response<Result> response) {
                try {
                   /* Log.e("Upload", "success:"+response.body());*/
                    Toast.makeText(PostActivity.this,"发布成功",Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(PostActivity.this,MainActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putInt("page",3);
                    intent.putExtras(bundle);
                    startActivity(intent);
                    finish();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onFailure(Call<Result> call, Throwable t) {
                Log.e("Upload error:", t.getMessage());
            }
        });
    }

    private void intview(){
        svg_back= (ImageView) findViewById(R.id.svg_back);
        post_content= (EditText) findViewById(R.id.post_content);
        add_postpic= (LinearLayout) findViewById(R.id.add_postpic);
        post_pic= (ImageView) findViewById(R.id.post_pic);
        btn_post= (RelativeLayout) findViewById(R.id.btn_post);
    }

    private void intEvent(){
        add_postpic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showChoosePicDialog();
            }
        });
        btn_post.setOnClickListener(new subPost());
        svg_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(PostActivity.this,MainActivity.class);
                Bundle bundle = new Bundle();
                bundle.putInt("page",3);
                intent.putExtras(bundle);
                startActivity(intent);
                finish();
            }
        });
    }

    /*获取Bitmap*/
    public String saveMyBitmap(String bitName,Bitmap mBitmap){
        File f = new File("/sdcard/" + bitName + ".jpg");
        String picPath="/sdcard/" + bitName + ".jpg";

        try {
            f.createNewFile();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            //  DebugMessage.put("在保存图片时出错："+e.toString());
        }
        FileOutputStream fOut = null;
        try {
            fOut = new FileOutputStream(f);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
        try {
            fOut.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fOut.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return picPath;
    }

}
